package com.wedo.mall.fragment;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.e.library.fragment.EFragment;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.EUtils;
import com.e.library.utils.EViewUtils;
import com.wedo.mall.R;
import com.wedo.mall.activity.LoginActivity;
import com.wedo.mall.activity.MainActivity;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.activity.order.OrderActivity;
import com.wedo.mall.activity.register.RegisterActivity;
import com.wedo.mall.adapter.ShoppingAdapter;
import com.wedo.mall.dialog.AttrDialog;
import com.wedo.mall.entity.AttrItem;
import com.wedo.mall.entity.Goods;
import com.wedo.mall.entity.Shopping;
import com.wedo.mall.util.WUtils;
import com.wedo.mall.widget.ShoppingView;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * 购物车
 * Created by lxy on 2017/6/8.
 */
public class ShoppingFragment extends EFragment<MainActivity> {

    @BindView(R.id.rl_un_login) RelativeLayout rl_un_login;
    @BindView(R.id.ll_empty) LinearLayout ll_empty;
    @BindView(R.id.ll_shopping) LinearLayout ll_shopping;
    @BindView(R.id.rv_shopping) RecyclerView rv_shopping;

    /**订单*/
    @BindView(R.id.rl_order) RelativeLayout rl_order;
    @BindView(R.id.tv_total_price) TextView tv_total_price;
    @BindView(R.id.tv_total_number) TextView tv_total_number;
    @BindView(R.id.cb_order) CheckBox cb_order;

    /**编辑*/
    @BindView(R.id.ll_edit) LinearLayout ll_edit;
    @BindView(R.id.tv_edit) TextView tv_edit;
    @BindView(R.id.cb_edit) CheckBox cb_edit;

    //@BindString(R.string.goods_price) String goods_price;
    String goods_price = "RM%.2f";
    @BindString(R.string.shopping_pieces) String shopping_pieces;

    private ShoppingAdapter mShoppingAdapter;

    public static ShoppingFragment with(){
        return new ShoppingFragment();
    }
    @Override
    protected int layout() {
        return R.layout.fragment_shopping;
    }

    @Override
    protected void onFragmentCreated(View contentView, Bundle bundle) {
        rv_shopping.setHasFixedSize(true);
        EViewUtils.vertical(rv_shopping);
        mShoppingAdapter = new ShoppingAdapter(getContext(),new ArrayList<Shopping>());
        rv_shopping.setAdapter(mShoppingAdapter);
        mShoppingAdapter.setOnObservableCheck(new ShoppingAdapter.OnObservableCheck() {
            @Override
            public void onChecked(boolean check) {
                cb_edit.setChecked(check);
                cb_order.setChecked(check);
                onShoppingChange(mShoppingAdapter.get());
            }
        });

        mShoppingAdapter.setAttrListener(new ShoppingView.OnAttrClickListener() {
            @Override
            public void onAttrClick(Goods goods) {
                ShoppingFragment.this.onAttrClick(goods);
            }
        });

        mShoppingAdapter.setOnDeleteGoods(new ShoppingAdapter.OnDeleteGoods() {
            @Override
            public void delete(Goods goods) {
                ShoppingFragment.this.delete(goods.id);
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();

        if (WLogin.logged(this)){
            rl_un_login.setVisibility(View.GONE);
            shopping();
        }else {
            ll_empty.setVisibility(View.GONE);
            ll_shopping.setVisibility(View.GONE);
            rl_un_login.setVisibility(View.VISIBLE);
        }
    }

    @OnClick(R.id.tv_edit)
    protected void onEditClick(){
        if (!WLogin.logged(this)){
            return;
        }

        if (mShoppingAdapter.isEmpty()){
            return;
        }

        if (tv_edit.isSelected()){
            normal();
        }else {
            edit();
        }
    }

    private void normal(){
        tv_edit.setSelected(false);
        tv_edit.setText(R.string.shopping_edit);
        ll_edit.setVisibility(View.GONE);
        rl_order.setVisibility(View.VISIBLE);
        mShoppingAdapter.editable(false);
        activity().number(mShoppingAdapter.get());
        onShoppingChange(mShoppingAdapter.get());
        editShoppingCar();
    }

    private void edit(){
        tv_edit.setSelected(true);
        tv_edit.setText(R.string.shopping_complete);
        rl_order.setVisibility(View.GONE);
        ll_edit.setVisibility(View.VISIBLE);
        mShoppingAdapter.editable(true);
    }

    @OnClick(R.id.btn_delete)
    protected void onDeleteClick(){
        String ids = ids();
        if(TextUtils.isEmpty(ids)) {
            return;
        }
        delete(ids);

    }

    @OnClick(R.id.btn_collection)
    protected void onCollectionClick(){
        String ids = ids();
        if(TextUtils.isEmpty(ids)) {
            return;
        }
        activity().loading();
        Observable<EResponse> observable =  EClient.with().api().moreCollect(ids);
        EClient.with().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                activity().dismiss(R.string.goods_collect_success);
            }

            @Override
            public void failure(String msg) {
                activity().dismiss(msg);
            }
        });
    }

    private void delete(String ids){
        activity().loading();
        Observable<EResponse> observable =  EClient.with().api().delShoppingCar(ids);
        EClient.with().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                activity().dismiss();
                shopping();
            }

            @Override
            public void failure(String msg) {
                activity().dismiss(msg);
            }
        });
    }

    /**多个商品ID以逗号分隔*/
    private String ids(){
        if(mShoppingAdapter.isEmpty()) {
            return null;
        }

        List<Shopping> list = mShoppingAdapter.get();

        StringBuilder ids = new StringBuilder();
        boolean hasMore = false;
        for (Shopping shopping:list){
            List<Goods> goods = shopping.goodsList;
            for (Goods g:goods){
                if (!g.check){
                    continue;
                }
                ids.append(hasMore?",":"");
                ids.append(g.id);
                hasMore = true;
            }
        }

        if(!hasMore) {
            return null;
        }

        return ids.toString();
    }

    @OnClick(R.id.btn_login)
    protected void onLoginClick(){
        Bundle bundle = new Bundle();
        bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
        activity().toActivity(LoginActivity.class,bundle);
    }

    @OnClick(R.id.btn_register)
    protected void onRegisterClick(){
        activity().toActivity(RegisterActivity.class);
    }

    @OnClick(R.id.btn_tourist)
    protected void onTouristClick(){
        activity().onTabChanged(0);
    }

    @OnClick(R.id.btn_order_all)
    protected void onOrderAllClick(){
        boolean c = onCheckClick(cb_order);
        cb_edit.setChecked(c);
    }

    @OnClick(R.id.btn_edit_all)
    protected void onEditAllClick(){
        boolean c = onCheckClick(cb_edit);
        cb_order.setChecked(c);
    }

    private boolean onCheckClick(CheckBox cb){
        if(cb.isChecked()) {
            cb.setChecked(false);
            mShoppingAdapter.check(false);
        }else {
            cb.setChecked(true);
            mShoppingAdapter.check(true);
        }
        onShoppingChange(mShoppingAdapter.get());

        return cb.isChecked();
    }

    @OnClick(R.id.btn_order)
    protected void onOrderClick(){
        if(mShoppingAdapter.isEmpty()) {
            return;
        }

        if(mShoppingAdapter.isCheckAll()) {
            List<Shopping> list = mShoppingAdapter.get();
            toOrder(list);
            return;
        }

        List<Shopping> list = mShoppingAdapter.get();
        List<Shopping> orders = new ArrayList<>();
        for (Shopping shopping:list){
            List<Goods> goodsList = shopping.goodsList;
            List<Goods> goodsOrder = new ArrayList<>();
            for (Goods goods:goodsList){
                if(goods.check) {
                    goodsOrder.add(goods);
                }
            }

            if(!goodsOrder.isEmpty()) {
                Shopping s = new Shopping();
                s.logo = shopping.logo;
                s.goodsList = goodsOrder;
                s.agent_name = shopping.agent_name;
                orders.add(s);
            }
        }

        if(!orders.isEmpty()) {
            toOrder(orders);
        }
    }

    /**确认订单*/
    private void toOrder(List<Shopping> orders){
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("orders",(ArrayList<? extends Parcelable>) orders);
        activity().toActivity(OrderActivity.class,bundle);
    }

    public void shopping(){
        EClient.with().post(EApi.SHOPPING_CAR, new EObserver() {
            @Override
            public void successful(EResponse response) {
                List<Shopping> list = response.list(Shopping.class);
                mShoppingAdapter.refresh(list);
                if (EUtils.isEmpty(list)){
                    onEmpty();
                }else {
                    ll_empty.setVisibility(View.GONE);
                    rl_order.setVisibility(View.VISIBLE);
                    ll_shopping.setVisibility(View.VISIBLE);
                    activity().number(list);

                    if (tv_edit.isSelected()){
                        edit();
                    }else {
                        normal();
                    }

                    cb_edit.setChecked(false);
                    cb_order.setChecked(false);
                }
            }

            @Override
            public void failure(String msg) {
                activity().toast(msg);
                onEmpty();
            }
        });
    }

    private void onEmpty(){
        ll_empty.setVisibility(View.VISIBLE);
        ll_shopping.setVisibility(View.GONE);

        tv_edit.setSelected(false);
        tv_edit.setText(R.string.shopping_edit);
        activity().number(0);
    }

    private void onShoppingChange(List<Shopping> list){
        int shoppingNumber = 0;
        double shoppingPrice = 0.00;
        for (Shopping shopping:list){
            List<Goods> goodsList = shopping.goodsList;
            for (Goods goods:goodsList){
                if(goods.check) {
                    shoppingNumber += goods.goods_number;
                    double price = WUtils.toDouble(goods.price())*goods.goods_number;
                    shoppingPrice += price;
                }
            }

        }

        tv_total_price.setText(String.format(goods_price,shoppingPrice));
        tv_total_number.setText(String.format(shopping_pieces,shoppingNumber));
    }

    /**修改购物车数量*/
    private void editShoppingCar(){
        List<Shopping> shoppings = mShoppingAdapter.get();
        List<Goods> changeList = new ArrayList<>();

        for (Shopping shopping:shoppings){
            List<Goods> goodsList = shopping.goodsList;
            for (Goods goods:goodsList){
                if(goods.shopping_change) {
                    changeList.add(goods);
                    goods.shopping_change = false;
                }
            }
        }

        if(changeList.isEmpty()) {
            return;
        }

        Observable.fromIterable(changeList).forEach(new Consumer<Goods>() {
            @Override
            public void accept(Goods goods) throws Exception {
                editShoppingCar(goods);
            }
        });
    }

    private void editShoppingCar(final Goods goods){

        Observable<EResponse> observable = EClient.with().api().editShoppingCar(goods.id,String.valueOf(goods.goods_number),goods.goods_id);
        EClient.with().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                goods.shopping_change = false;
            }

            @Override
            public void failure(String msg) {
                activity().toast(msg);
            }
        });
    }

    private void onAttrClick(final Goods goods){
        final AttrDialog dialog = AttrDialog.with(goods);
        dialog.widget.setOnSelectedAttr(new AttrFragment.OnSelectedAttr() {
            @Override
            public void onSelected(String id, int number, Collection<AttrItem> attrs) {
                goods.goods_id = id;
                goods.goods_number = number;
                goods.shopping_change = true;
                if(goods.attrList == null) {
                    goods.attrList = new ArrayList<>(attrs);
                }else {
                    goods.attrList.clear();
                    goods.attrList.addAll(attrs);
                }
                mShoppingAdapter.notifyDataSetChanged();
                dialog.dismiss();
            }
        });

        dialog.show(activity().getSupportFragmentManager());
    }
}
